<style>
table.lo * { font-size: 12px; font-family: Trebuchet MS; }
table.lo { width: 100%; }
table.lo td { vertical-align: top; text-align: left; }
table.lo td.left { width: 500px; }
table.lo td.middle { width: 400px; }
table.lo td.right { width: 400px; }
.pure_table_extra { width: 1100px; margin-top: 5px; }
.pure_table_extra th { height: 25px; line-height: 25px; }
.pure_table_extra img { cursor: pointer; margin-right: 2px; }
.pure_table_extra td { vertical-align: middle; }
.pure_table_extra input[type=text] { height: 25px !important; }
.chosen-choices input { height: 25px !important; width: 100% !important; }
.chosen-choices { width: 215px !important; }
</style>

<?php 
$date = date('Y-m-d', time());
$student_id = Utils::get_param('id', 0);

$user = json_decode($_SESSION['admin_user']);
if ($user->role == UT_ADMIN) {
  $agents = $orm->get('pb_colg_agent', 't.company', 'ASC', NULL, NULL, NULL)->d;
} else {
  $opts = new stdClass();
  $opts->cd = 't.user_id LIKE :v1';
  $opts->cdv = array(':v1' => '%,' . $user->id . ',%');
  $agents = $orm->get('pb_colg_agent', 't.agent', 'ASC', NULL, NULL, $opts)->d;
}

$opts = new stdClass();
$opts->cd = 't.student_id = :v1 AND t.program_type != :v2';
$opts->cdv = array(':v1' => $student_id, ':v2' => PT_LANGUAGE);
$opts->sel = 't.*, t1.type AS __type, t1.name AS __name';
$opts->jt = 'LEFT JOIN pb_colg_program AS t1 ON t1.id = t.program_id';
$enrlprograms = $orm->get('pb_colg_enrolled_program', 't.id', 'DESC', NULL, NULL, $opts)->d;

$programs = $orm->get('pb_colg_program', 't.name', 'ASC', NULL, NULL, NULL)->d;

$opts = new stdClass();
$opts->cd = 't.type = :v1';
$opts->cdv = array(':v1' => PT_DIPLOMA);
$intakes = $orm->get('pb_colg_intake', 't.start', 'DESC', NULL, NULL, $opts)->d;

$opts = new stdClass();
$opts->cd = 't.type = :v1';
$opts->cdv = array(':v1' => PT_NCEA);
$intakes2 = $orm->get('pb_colg_intake', 't.start', 'DESC', NULL, NULL, $opts)->d;


$bpts = unserialize(BPTS);
?>

<div id="dialog_enrl" class="pure-form" style="display: none; overflow: visible;" title="Enrollment">
  <h3 class="fl">File List</h3>
  <div class="fl"></div>
  <h3 class="pay">Invoices & Payments</h3>
  <div class="pay">
    <span style="padding: 5px 10px; font-weight: bold;" id="pay_status" class="ui-corner-all"></span>
    <span style="float: right;"><input id="dft_adddate" style="width: 80px;" value="<?php echo $date; ?>"></input></span>
    <div>&nbsp;</div>
    <table class="pure-table pure_table_extra">
      <thead>
        <tr>
          <th style="width: 80px;" class="ui-widget-header">Invoice ID</th>
          <th style="width: 120px;" class="ui-widget-header">Particular</th>
          <th style="width: 60px;" class="ui-widget-header">From</th>
          <th style="width: 60px;" class="ui-widget-header">To</th>
          <th style="width: 60px;" class="ui-widget-header">Amount</th>
          <th style="width: 60px;" class="ui-widget-header">Paid</th>
          <th style="width: 70px;" class="ui-widget-header">Discount +/-</th>
          <th style="width: 80px;" class="ui-widget-header">Due Date</th>
          <th class="ui-widget-header">Note</th>
          <th style="width: 80px;" class="ui-widget-header">Balance</th>
          <th style="width: 80px;" class="ui-widget-header">Date</th>
        </tr>
      </thead>
      <tbody id="pay_body"></tbody>
    </table>
  </div>
  <h3>Basic</h3>
  <div>
    <table class="lo" cellPadding="0" cellSpacing="0">
      <tr>
        <td class="left">
          <div class="pure-form pure-form-aligned pure_form_extra">
            <legend>System Log</legend>
            
            <div class="pure-control-group" style="display: none;">
              <label>Enrollment ID</label>
              <input id="id" type="text" class="pure-input-1-2" placeholder="{ID}" readonly="true" />
            </div>
            
            <div class="pure-control-group">
              <label>Student</label>
              <input id="student" type="text" class="pure-input-1-2" placeholder="{Student}" readonly="true" />
            </div>
            
            <div class="pure-control-group">
              <label>User</label>
              <input id="marketing" type="text" class="pure-input-1-2" placeholder="{User}" readonly="true" />
            </div>
            
            <div class="pure-control-group">
              <label>Date</label>
              <input id="date" type="text" class="pure-input-1-2" placeholder="{Date}" readonly="true" />
            </div>
          </div>
          
          <div>&nbsp;</div>
            
          <div class="pure-form pure-form-aligned pure_form_extra">
            <legend>Info</legend>
            
            <div class="pure-control-group">
              <label>Trial</label>
              <input id="trial" type="checkbox"></input>
            </div>
            
            <div class="pure-control-group">
              <label>Agent</label>
              <select id="agent" class="pure-input-1-2"></select>
            </div>
            
            <div class="pure-control-group">
              <label>Reg Date</label>
              <input id="reg_date" type="text" class="pure-input-1-2" placeholder="{Reg Date}" />
            </div>
            
            <div class="pure-control-group">
              <label>Enrolled for</label>
              <select id="type" class="pure-input-1-2">
                <option value="0">New program</option>
                <option value="1">Continue to study</option>
              </select>
            </div>
          
            <div class="pure-control-group">
              <label>Enrolled Program</label>
              <select id="program" class="pure-input-1-2"></select>
            </div>
            
            <div id="papers_div" class="pure-control-group">
              <label>Papers</label>
              <input id="papers" type="text" class="pure-input-1-2" placeholder="{Papers}" />
            </div>
            
            <div id="intakes_div" class="pure-control-group">
              <label>Intakes</label>
              <span id="intakes"></span>
            </div>
            
            <div id="intakes_div" class="pure-control-group">
              <label>Type</label>
              <span id="repeat">
                <input type="radio" id="repeat0" name="repeat" onclick="$('#enrl_type_note').val('Fulltime');" checked="checked"><label style="width: 70px !important;" for="repeat0">Fulltime</label>
                <input type="radio" id="repeat1" name="repeat" onclick="$('#enrl_type_note').val('Part Time');"><label style="margin-left: -17px;width: 80px !important;" for="repeat1">Part Time</label>
                <input type="radio" id="repeat11" name="repeat" onclick="$('#enrl_type_note').val('');"><label style="margin-left: -17px;width: 70px !important;" for="repeat11">Other</label>
              </span>
            </div>
            
            <div id="papers_div" class="pure-control-group">
              <label>&nbsp;</label>
              <input id="enrl_type_note" type="text" class="pure-input-1-2" placeholder="{e.g. Last two courses}" value="Fulltime"/>
            </div>
            
            <div id="papers_div" class="pure-control-group">
              <label>Papers</label>
              <input id="papers" type="text" class="pure-input-1-2" placeholder="{Papers}" />
            </div>
            
            <div class="pure-control-group">
              <label>Note</label>
              <textarea id="note" style="resize: none; height: 100px;" class="pure-input-1-2" placeholder="{Note}"></textarea>
            </div>
          </div>
        </td>
        <td class="middle">
          <div class="pure-form pure-form-aligned pure_form_extra">
            <legend>Tuition</legend>
            
            <div class="pure-control-group">
              <label>Start</label>
              <input id="start_academic" type="text" class="pure-input-1-2" placeholder="{Start}" />
            </div>
          
            <div class="pure-control-group">
              <label>Weeks</label>
              <input id="weeks_academic" type="text" class="pure-input-1-2" placeholder="{Weeks}" />
            </div>
            
            <div class="pure-control-group">
              <label>End</label>
              <input id="end_academic" type="text" class="pure-input-1-2" placeholder="{End}" />
            </div>
            
            <div class="pure-control-group">
              <label>Tuition Fee</label>
              <input id="total_academic" type="text" class="pure-input-1-2" placeholder="{Tuition Fee}" />
            </div>
            
            <div class="pure-control-group">
              <label>Admin Fee</label>
              <input id="fee_admin" type="text" class="pure-input-1-2" placeholder="{Admin Fee}" />
            </div>
            
            <div class="pure-control-group">
              <label>Airport Pickup Fee</label>
              <input id="fee_pickup" type="text" class="pure-input-1-2" placeholder="{Airport Pickup Fee}" />
            </div>
            
            <div class="pure-control-group">
              <label>Exam Fee</label>
              <input id="fee_exam" type="text" class="pure-input-1-2" placeholder="{Exam Fee}" />
            </div>
            
            <div class="pure-control-group">
              <label>Homestay Admin fee</label>
              <input id="fee_homestay" type="text" class="pure-input-1-2" placeholder="{Homestay Admin fee}" />
            </div>
            
            <div class="pure-control-group" style="display: none;">
              <label>Living Fee</label>
              <input id="fee_living" type="text" class="pure-input-1-2" placeholder="{Living Fee}" />
            </div>
            
            <div class="pure-control-group">
              <label>Material Fee</label>
              <input id="fee_material" type="text" class="pure-input-1-2" placeholder="{Material Fee}" />
            </div>
            
            <div class="pure-control-group">
              <label>Registration Fee</label>
              <input id="fee_registration" type="text" class="pure-input-1-2" placeholder="{Registration Fee}" />
            </div>
            
            <div class="pure-control-group">
              <label>Other Fee</label>
              <input id="fee_other" type="text" class="pure-input-1-2" placeholder="{Other Fee}" />
            </div>
          </div>
        </td>
        <td class="right">
          <div class="pure-form pure-form-aligned pure_form_extra">
            <legend>Accommodation</legend>
            
            <div class="pure-control-group">
              <label>Start</label>
              <input id="start_accommodation" type="text" class="pure-input-1-2" placeholder="{Start}" />
            </div>
          
            <div class="pure-control-group">
              <label>Weeks</label>
              <input style="width: 60px;" id="weeks_accommodation" type="text" placeholder="{Weeks}" /> * <input style="width: 60px;" id="price_accommodation" type="text" placeholder="{Price}" />
            </div>
            
            <div class="pure-control-group">
              <label>End</label>
              <input id="end_accommodation" type="text" class="pure-input-1-2" placeholder="{End}" />
            </div>
            
            <div class="pure-control-group">
              <label>Fee</label>
              <input id="total_accommodation" type="text" class="pure-input-1-2" placeholder="{Fee}" />
            </div>
          </div>
          <div>&nbsp;</div>
          <div class="pure-form pure-form-aligned pure_form_extra">
            <legend>Insurance</legend>
            
            <div class="pure-control-group">
              <label>Start</label>
              <input id="start_insurance" type="text" class="pure-input-1-2" placeholder="{Start}" />
            </div>
          
            <div class="pure-control-group">
              <label>Month</label>
              <input id="months_insurance" type="text" class="pure-input-1-2" placeholder="{Months}" />
            </div>
            
            <div class="pure-control-group">
              <label>End</label>
              <input id="end_insurance" type="text" class="pure-input-1-2" placeholder="{End}" />
            </div>
            
            <div class="pure-control-group">
              <label>Fee</label>
              <input id="total_insurance" type="text" class="pure-input-1-2" placeholder="{Fee}" />
            </div>
          </div>
        </td>
      </tr>
    </table>
  </div>
</div>

<script>
  /*<![CDATA[*/
  var ____agents = JSON.parse('<?php echo addslashes(json_encode($agents)); ?>');
  var ____enrlprograms = JSON.parse('<?php echo addslashes(json_encode($enrlprograms)); ?>');
  var ____programs = JSON.parse('<?php echo addslashes(json_encode($programs)); ?>');
  var ____intakes = JSON.parse('<?php echo addslashes(json_encode($intakes)); ?>');
  var ____intakes2 = JSON.parse('<?php echo addslashes(json_encode($intakes2)); ?>');
  var ____diploma = '<?php echo PT_DIPLOMA; ?>';
  var ____ncea = '<?php echo PT_NCEA; ?>';
  var ____date = '<?php echo $date; ?>';
  var ____bpts = JSON.parse('<?php echo addslashes(json_encode($bpts)); ?>');
  
  $(function() {
    $('#repeat').buttonset()
      
    $('#agent').append('<option value="0"></option>');
    for (var idx in ____agents) {
      var itm = ____agents[idx];
      $('#agent').append('<option value="' + itm.id + '">' + itm.company + '</option>');
    }
    $('#agent').chosen({
      allow_single_deselect: true
    });
    $('#agent_chosen').css('width', '190px');
    
    $('#type').on('change', function() {
      if (this.value == 1) {
        if (____enrlprograms.length > 0) {
          this.__obj.enrolled_program_id = ____enrlprograms[0].id;
          this.__obj.program_id = ____enrlprograms[0].program_id;
          this.__obj.program_name = ____enrlprograms[0].__name;
          this.__obj.program_type = ____enrlprograms[0].__type;
        }
      } else {
        this.__obj.enrolled_program_id = 0;
        this.__obj.program_id = ____programs[0].id;
        this.__obj.program_name = ____programs[0].name;
        this.__obj.program_type = ____programs[0].type;
      }
      ____program(this.__obj);
    });

    $('#program').on('change', function() {
      if ($('#type :selected').val() == 0) {
        var p = Utils.get_by_id(this.value, ____programs);
        this.__obj.program_id = p.id;
        this.__obj.program_name = p.name;
        this.__obj.program_type = p.type;
      } else {
        var ep = Utils.get_by_id(this.value, ____enrlprograms);
        this.__obj.enrolled_program_id = ep.id;
        this.__obj.program_id = ep.program_id;
        this.__obj.program_name = ep.__name;
        this.__obj.program_type = ep.__type;
      }
      ____program(this.__obj);
    });
    
    $('#reg_date').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd"
    });

    $('#start_academic').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      onSelect: function(dateText) {
        var s = Utils.str_to_date(dateText);
        $('#end_academic').val(Utils.date_to_str(new Date(s.getTime() + (86400 * 1000 * ($('#weeks_academic').val() * 7)))));
      },
      beforeShowDay: function(date) {
        var day = date.getDay();
        return [(day == 1), ''];
      }
    });

    $('#weeks_academic').on('change', function() {
      var s = Utils.str_to_date($('#start_academic').val());
      $('#end_academic').val(Utils.next_friday(Utils.date_to_str(new Date(s.getTime() + (this.value * (86400 * 1000 * 7) - (86400 * 1000 * 3))))));
    });

    $('#end_academic').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      onSelect: function(dateText) {
//        var e = Utils.str_to_date(dateText);
//        $('#start_academic').val(Utils.date_to_str(new Date(e.getTime() - (86400 * 1000 * ($('#weeks_academic').val() * 7)))));
      },
      beforeShowDay: function(date) {
        var day = date.getDay();
        return [(day == 5), ''];
      }
    });

    $('#start_accommodation').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      onSelect: function(dateText) {
        var s = Utils.str_to_date(dateText);
        $('#end_accommodation').val(Utils.date_to_str(new Date(s.getTime() + (86400 * 1000 * ($('#weeks_accommodation').val() * 7)))));
      }
    });

    $('#weeks_accommodation').on('change', function() {
      var s = Utils.str_to_date($('#start_accommodation').val());
      $('#end_accommodation').val(Utils.date_to_str(new Date(s.getTime() + this.value * (86400 * 1000 * 7))));
      $('#total_accommodation').val(($('#weeks_accommodation').val() * $('#price_accommodation').val()).toFixed(2));
    });

    $('#price_accommodation').on('change', function() {
      $('#total_accommodation').val(($('#weeks_accommodation').val() * $('#price_accommodation').val()).toFixed(2));
    });

    $('#end_accommodation').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      onSelect: function(dateText) {
        var e = Utils.str_to_date(dateText);
        $('#start_accommodation').val(Utils.date_to_str(new Date(e.getTime() - (86400 * 1000 * ($('#weeks_accommodation').val() * 7)))));
      }
    });

    $('#start_insurance').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      onSelect: function(dateText) {
        var s = Utils.str_to_date(dateText);
        var e = Utils.str_to_date($('#end_insurance').val());
        $('#months_insurance').val(parseInt((e.getTime() - s.getTime()) / (86400 * 1000 * 30), 10));
      }
    });

    $('#months_insurance').on('change', function() {
      var s = Utils.str_to_date($('#start_insurance').val());
      $('#end_insurance').val(Utils.date_to_str(new Date(s.getTime() + this.value * (86400 * 1000 * 30))));
    });

    $('#end_insurance').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      onSelect: function(dateText) {
        var s = Utils.str_to_date($('#start_insurance').val());
        var e = Utils.str_to_date(dateText);
        $('#months_insurance').val(parseInt((e.getTime() - s.getTime()) / (86400 * 1000 * 30), 10));
      }
    });
  });

  function ____set_fees(obj) {
    obj.__fees = [];
    for (var idx in obj) {
      var itm = obj[idx];
      if ((idx.indexOf('fee_') != -1 || idx.indexOf('total_')) != -1 && itm > 0) {
        obj.__fees.push(____fee_c(obj, idx));
      }
    }
  };

  function ____fee_c(obj, attr) {
    var rslt = {
      balance__: '0.00',
      to_trustaccount: 1,
      track_id: '#' + Utils.unique(8),
      student_id: obj.student_id,
      student_title__: obj.student_title__,
      user_id: obj.user_id,
      user_title__: obj.user_title__,
      enrollment_id: obj.id,
      enrollment_track_id: obj.track_id,
      particular: ____bpts[attr],
      date: ____date,
      due_date: ____date,
      amount: obj[attr],
      from: obj.start_academic,
      to: obj.end_academic,
      comment: 'ENRL ' + obj.track_id,
      __paid: parseFloat(obj[attr], 10).toFixed(2),
      __discount: '0.00'
    };
    if (attr == 'total_accommodation') {
      rslt.from = obj.start_accommodation;
      rslt.to = obj.end_accommodation;
    }
    if (attr == 'total_insurance') {
      rslt.from = obj.start_insurance;
      rslt.to = obj.end_insurance;
    }
    return rslt;
  }
  
  function ____bal_fees(obj) {
    for (var idx in obj.__fees) {
      var itm = obj.__fees[idx];
      itm.__discount = (itm.amount - itm.__paid).toFixed(2);
      itm.balance__ = '0.00';
    };
  }
  
  function ____render_fees(obj) {
    var total_due, total_paid, total_discount;

    total_due = 0
    total_paid = 0;
    total_discount = 0;
    for (var idx in obj) {
      var itm = obj[idx];
      if ((idx.indexOf('fee_') != -1 || idx.indexOf('total_')) != -1 && itm > 0) {
        total_due += parseFloat(itm, 10);
      }
    }
    
    $("#pay_body").empty();
    for (var idx in obj.__fees) {
      var itm = obj.__fees[idx];
      $('#pay_body').append(
        '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td>' + itm.track_id + '</td>' +
          '<td title="' + itm.particular + '">' + Utils.get_short(itm.particular, 12) + '</td>' +
          '<td>' + itm.from + '</td>' +
          '<td>' + itm.to + '</td>' +
          '<td>' + accounting.formatMoney(itm.amount) + '</td>' +
          '<td><input style="width: 100%;" id="paid_' + itm.track_id.replace('#', '') + '" type="text" value="' + itm.__paid + '" /></td>' +
          '<td><input style="width: 100%;" id="disc_' + itm.track_id.replace('#', '') + '" type="text" value="' + itm.__discount + '" /></td>' +
          '<td><input style="width: 100%;" id="duedate_' + itm.track_id.replace('#', '') + '" type="text" value="' + itm.due_date + '" /></td>' +
          '<td title="' + itm.comment + '">' + Utils.get_short(itm.comment, 50) + '</td>' +
          '<td>' + accounting.formatMoney(itm.balance__) + ((itm.balance__ == 0) ? '<i style="color: green; float: right;" class="fa fa-check-circle"></i>' : '<i style="color: red; float: right;" class="fa fa-times-circle"></i>') + '</td>' +
          '<td><input style="width: 100%;" id="adddate_' + itm.track_id.replace('#', '') + '" type="text" value="' + itm.date + '" /></td>' +
        '</tr>'
      );

      $('#paid_' + itm.track_id.replace('#', '')).on('change', function() {
        for (var idx2 in obj.__fees) {
          var itm2 = obj.__fees[idx2];
          if (itm2.track_id == this.id.replace('paid_', '#')) {
            itm2.__paid = parseFloat(this.value, 10).toFixed(2);
            itm2.balance__ = (parseFloat(itm2.__paid, 10) + parseFloat(itm2.__discount, 10) - parseFloat(itm2.amount, 10)).toFixed(2);
          }
        }
        ____bal_fees(obj);
        ____render_fees(obj);
      });
      $('#disc_' + itm.track_id.replace('#', '')).on('change', function() {
        for (var idx2 in obj.__fees) {
          var itm2 = obj.__fees[idx2];
          if (itm2.track_id == this.id.replace('disc_', '#')) {
            itm2.__discount = parseFloat(this.value, 10).toFixed(2);
            itm2.balance__ = (parseFloat(itm2.__paid, 10) + parseFloat(itm2.__discount, 10) - parseFloat(itm2.amount, 10)).toFixed(2);
          }
        }
        ____render_fees(obj);
      });
      $('#duedate_' + itm.track_id.replace('#', '')).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: "yy-mm-dd",
        onSelect: function(dateText) {
          for (var idx2 in obj.__fees) {
            var itm2 = obj.__fees[idx2];
            if (itm2.track_id == this.id.replace('duedate_', '#')) {
              itm2.due_date = dateText;
            }
          };
          ____render_fees(obj);
        }
      });
      $('#adddate_' + itm.track_id.replace('#', '')).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: "yy-mm-dd",
        onSelect: function(dateText) {
          for (var idx2 in obj.__fees) {
            var itm2 = obj.__fees[idx2];
            if (itm2.track_id == this.id.replace('adddate_', '#')) {
              itm2.date = dateText;
            }
          };
          ____render_fees(obj);
        }
      });
      
      total_paid += parseFloat(itm.__paid, 10);
      total_discount += parseFloat(itm.__discount, 10);
    }
    if (obj.__fees.length == 0) {
      $('#pay_body').append('<tr class="pure-table-even"><td colspan=10>None</td></tr>');
    }
    
    if ((total_discount + total_paid - total_due) != 0) {
      $('#pay_status').html('Received: ' + accounting.formatMoney(total_paid) + ' + (' + accounting.formatMoney(total_discount) + '), Balance: ' + accounting.formatMoney(total_discount + total_paid - total_due) + ' (Invoice Total: ' + accounting.formatMoney(total_due) + ')');
      $('#pay_status').addClass('ui-state-error');
      $('#pay_status').removeClass('ui-state-highlight');
    } else {
      $('#pay_status').html('Received: ' + accounting.formatMoney(total_paid) + '&nbsp;&nbsp;<i style="color: green;" class="fa fa-check-circle"></i>');
      $('#pay_status').removeClass('ui-state-error');
      $('#pay_status').addClass('ui-state-highlight');
    }
  };

  function ____enrl(obj, opts) {
    $('#dft_adddate').parent().html('<input id="dft_adddate" style="width: 80px;" value="' + __date + '"></input>');
    $('#dft_adddate').datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      onSelect: function(dateText) {
        for (var idx in obj.__fees) {
          var itm = obj.__fees[idx];
          itm.date = dateText;
        };
        ____render_fees(obj);
      }
    });
    
    $("#dialog_enrl").dialog('option', 'title', 'Enrollment ' + ((obj.track_id != undefined) ? obj.track_id : 'New'));
    
    if (opts && opts.m == 'pay' && obj.is_paid == 1) {
      ____enrl_c(obj, opts);
      $("#pay *").prop('disabled', 'disabled');
      $("#pay input[type=text]").css('background', 'white');
    } else {
      ____set_fees(obj);
      ____enrl_c(obj, opts);
    }

    $(".lo input[type=text]").css('background', 'white');
    $(".pay input[type=text]").css('background', 'white');
    if (opts && (opts.m == 'pay' || opts.m == 'fl')) {
      $(".lo *").prop('disabled', 'disabled');
      $(".lo *").prop('disabled', 'disabled').trigger("chosen:updated");
      if (obj.is_paid == 1) {
        $(".pay *").prop('disabled', 'disabled');
      }
    } else if (obj.is_paid == 1) {
      $(".lo *").prop('disabled', 'disabled');
      $(".lo *").prop('disabled', 'disabled').trigger("chosen:updated");
//      $("#start_academic").removeAttr('disabled');
//      $("#start_accommodation").removeAttr('disabled');
//      $("#start_insurance").removeAttr('disabled');
      $("#comment").removeAttr('disabled');
    } else {
      $(".lo *").removeAttr('disabled');
      $(".lo *").removeAttr('disabled').trigger("chosen:updated");
      $("#id").prop('disabled', 'disabled');
      $("#student").prop('disabled', 'disabled');
      $("#date").prop('disabled', 'disabled');
      $("#marketing").prop('disabled', 'disabled');
      $('#agent').chosen({
        allow_single_deselect: true
      });
      $('#agent_chosen').css('width', '190px');
    }
    $("#repeat").buttonset('refresh');
  };

  function ____enrl_c(obj, opts) {
    if (opts && opts.m == 'pay') {
      $(".fl").remove();
      ____render_fees(obj)
    } else if (opts && opts.m == 'fl') {
      $(".pay").remove();
    } else {
      $(".fl").remove();
      $(".pay").remove();
    }
    $("#dialog_enrl").accordion({
      heightStyle: "content",
      collapsible:true,
      beforeActivate: function(event, ui) {
        // The accordion believes a panel is being opened
        if (ui.newHeader[0]) {
          var currHeader  = ui.newHeader;
          var currContent = currHeader.next('.ui-accordion-content');
          // The accordion believes a panel is being closed
        } else {
          var currHeader  = ui.oldHeader;
          var currContent = currHeader.next('.ui-accordion-content');
        }
        // Since we've changed the default behavior, this detects the actual status
        var isPanelSelected = currHeader.attr('aria-selected') == 'true';
        // Toggle the panel's header
        currHeader.toggleClass('ui-corner-all',isPanelSelected).toggleClass('accordion-header-active ui-state-active ui-corner-top',!isPanelSelected).attr('aria-selected',((!isPanelSelected).toString()));
        // Toggle the panel's icon
        currHeader.children('.ui-icon').toggleClass('ui-icon-triangle-1-e',isPanelSelected).toggleClass('ui-icon-triangle-1-s',!isPanelSelected);
        // Toggle the panel's content
        currContent.toggleClass('accordion-content-active',!isPanelSelected)    
        if (isPanelSelected) { currContent.slideUp(); }  else { currContent.slideDown(); }
        return false; // Cancel the default action
      }
    });
    
    if (obj.is_trial == 1) {
      $("#trial").prop('checked', 'checked');
    } else {
      $("#trial").removeAttr('checked');
    }
    
    $("#id").val(obj.id == 0 ? '{New}' : obj.track_id);
    $("#student").val(obj.student_title__);
    $("#date").val(obj.date);
    
    $("#reg_date").val(obj.reg_date);
    $('#marketing').val(obj.user_title__);
    $("#agent").val(obj.agent_id);
    
    ____program(obj);
    
    $("#papers").val(obj.papers);
    $("#note").val(obj.note);

    $("#start_academic").val(obj.start_academic);
    $("#end_academic").val(obj.end_academic);
    $("#weeks_academic").val(obj.weeks_academic);
    $("#total_academic").val(obj.total_academic);

    $("#fee_admin").val(obj.fee_admin);
    $("#fee_pickup").val(obj.fee_pickup);
    $("#fee_exam").val(obj.fee_exam);
    $("#fee_homestay").val(obj.fee_homestay);
    $("#fee_living").val(obj.fee_living);
    $("#fee_material").val(obj.fee_material);
    $("#fee_registration").val(obj.fee_registration);
    $("#fee_other").val(obj.fee_other);

    $("#start_accommodation").val(obj.start_accommodation);
    $("#end_accommodation").val(obj.end_accommodation);
    $("#weeks_accommodation").val(obj.weeks_accommodation);
    $("#price_accommodation").val(obj.price_accommodation);
    $("#total_accommodation").val(obj.total_accommodation);

    $("#start_insurance").val(obj.start_insurance);
    $("#end_insurance").val(obj.end_insurance);
    $("#months_insurance").val(obj.months_insurance);
    $("#total_insurance").val(obj.total_insurance);
    
    $("#agent").trigger("chosen:updated");

    if (obj.enrl_type_note == 'Fulltime') {
      $("#repeat0").prop("checked", true)
    } else if (obj.enrl_type_note == 'Part Time') {
      $("#repeat1").prop("checked", true)
    } else {
      $("#repeat11").prop("checked", true)
    }
    $('#repeat').buttonset('refresh');
    $("#enrl_type_note").val(obj.enrl_type_note);
  };
  
  function ____program(obj) {
    $('#type')[0].__obj = obj;
    $('#program')[0].__obj = obj;
    if (____enrlprograms.length == 0) {
      $('#type')[0].options[1].disabled = 'disabled';
    }

    $('#program').empty();
    if (obj.enrolled_program_id != 0) {
      $("#type").val(1);
      for (var idx in ____enrlprograms) {
        var itm = ____enrlprograms[idx];
        $('#program').append('<option value="' + itm.id + '">' + itm.__name + '</option>');
      }
      $('#program').val(obj.enrolled_program_id);
    } else {
      $("#type").val(0);
      for (var idx in ____programs) {
        var itm = ____programs[idx];
        $('#program').append('<option value="' + itm.id + '">' + itm.name + '</option>');
      }
      $('#program').val(obj.program_id);
    }

    if (obj.program_type == ____diploma) {
      $('#papers_div').show();
      $('#intakes_div').show();
    } else {
      $('#papers_div').hide();
      if (obj.program_type == ____ncea) {
        $('#intakes_div').show();
      } else {
        $('#intakes_div').hide();
      }
    }

    $("#intakes").empty();
    var itks = [];
    if (obj.program_type == ____diploma) {
      itks = ____intakes;
    } else if (obj.program_type == ____ncea) {
      itks = ____intakes2;
    }
    $("#intakes").append('<select multiple onchange="update_period();"></select>');
    for (var idx in itks) {
      var itm = itks[idx];
      if (itm.programs__.indexOf(',' + obj.program_id + ',') == -1 && obj.program_type != ____ncea) {
        continue;
      }
      var exist = false;
      $("#intakes select").append('<option ' + ((obj.intakes__.indexOf(',' + itm.id + ',') != -1) ? 'selected="selected" ' : '') + 'value="' + itm.id + '">' + ((itm.type_ncea != '') ? '(' + itm.type_ncea + ') ' : '') + itm.start + ' to ' + itm.end + '</option>');
    }
    $("#intakes select").chosen();
  };

  function update_period() {
    var itks = $("#intakes select").val();
    var start = '9999-99-99', end = '0000-00-00';
    for (var idx in ____intakes) {
      var itm = ____intakes[idx];
      if ($.inArray(itm.id, itks) !== -1) {
        if (start.localeCompare(itm.start) > 0) {
          start = itm.start;
        }
        if (end.localeCompare(itm.end) < 0) {
          end = itm.end;
        }
      }
    }
    for (var idx in ____intakes2) {
      var itm = ____intakes2[idx];
      if ($.inArray(itm.id, itks) !== -1) {
        if (start.localeCompare(itm.start) > 0) {
          start = itm.start;
        }
        if (end.localeCompare(itm.end) < 0) {
          end = itm.end;
        }
      }
    }
    
    if (start != '9999-99-99' && end != '0000-00-00') {
      $('#start_academic').val(start);
      $('#end_academic').val(end);
      $('#weeks_academic').val(Math.round((Utils.str_to_date(end).getTime() - Utils.str_to_date(start).getTime()) / (86400000 * 7)));
    }
  };
  /*]]>*/
</script>